﻿using DocBot.Bot;
using DocBot.Objects;
using DocBot.Util;

using Ookii.Dialogs.Wpf;

using System.Diagnostics;
using System.IO;
using System;
using System.Windows;
using System.Windows.Data;

namespace DocBot
{
	/// <summary>
	/// Interaktionslogik für MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		private InsireBot _bot;

		public InsireBot Bot
		{
			get { return _bot; }
		}

		private MediaPlayer _player;
		private MediaPlayer _followerAlert;
		private MediaPlayer _subscriberAlert;
		private MediaPlayer _soundBoard;

		private bool initializedMainWindow = false;

		public MainWindow()
		{
			InitializeComponent();
			initializedMainWindow = true;

			_bot = new InsireBot(this);
			//checkVLC(ref _player);
			//checkVLC(ref _followerAlert);
			//checkVLC(ref _subscriberAlert);
			//checkVLC(ref _soundBoard);
		}

		#region Settings
		private void tbVLCLibDLL_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
		{
			VistaFolderBrowserDialog dialog = new VistaFolderBrowserDialog();
			dialog.Description = "Please select a folder.";
			dialog.UseDescriptionForTitle = true; // This applies to the Vista style dialog only, not the old dialog.
			DirSearch(Directory.GetCurrentDirectory());
			dialog.SelectedPath = Settings.Instance.VLC_LibVlcDllPath;
			if (!VistaFolderBrowserDialog.IsVistaFolderDialogSupported)
			{
				MessageBox.Show(this, "Because you are not using Windows Vista or later, you have to fill in the path by yourself", "Not Supported");
			}
			if ((bool)dialog.ShowDialog(this))
			{
				tbVLCLibDLL.Text = dialog.SelectedPath;
			}
		}

		private void tbVLCPlugins_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
		{
			VistaFolderBrowserDialog dialog = new VistaFolderBrowserDialog();
			dialog.Description = "Please select a folder.";
			dialog.UseDescriptionForTitle = true; // This applies to the Vista style dialog only, not the old dialog.
			DirSearch(Directory.GetCurrentDirectory());
			dialog.SelectedPath = Settings.Instance.VLC_LibVlcDllPath;
			if (!VistaFolderBrowserDialog.IsVistaFolderDialogSupported)
			{
				tbVLCLibDLL.Text = dialog.SelectedPath;
			}
			if ((bool)dialog.ShowDialog(this))
			{
				tbVLCPlugins.Text = dialog.SelectedPath;
			}
		}

		void DirSearch(string sDir)
		{
			try
			{
				foreach (string d in Directory.GetDirectories(sDir))
				{
					foreach (string f in Directory.GetFiles(d))
					{
						if (f.Contains("vlc.exe"))
						{
							Settings.Instance.VLC_LibVlcDllPath = d;
							return;
						}
					}
					DirSearch(d);
				}
			}
			catch (System.Exception e)
			{
				System.Console.WriteLine(e.InnerException);
			}
		}

		private void cbPlaymode_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
		{
			Settings.Instance.VLC_PlayBackType = (Playmode)cbPlaymode.SelectedValue;
		}
		#endregion

		#region MediaPlayerGUIEvents
		private void bPlay_Click(object sender, RoutedEventArgs e)
		{
			if (checkVLC(ref _player, AudioDeviceType.MediaPlayer))
				_player.play();
		}

		private void bPrevious_Click(object sender, RoutedEventArgs e)
		{
			if (checkVLC(ref _player, AudioDeviceType.MediaPlayer))
				_player.Previous();
		}

		private void bStop_Click(object sender, RoutedEventArgs e)
		{
			if (checkVLC(ref _player, AudioDeviceType.MediaPlayer))
				_player.Stop();
		}

		private void bRandom_Click(object sender, RoutedEventArgs e)
		{
			if (checkVLC(ref _player, AudioDeviceType.MediaPlayer))
				_player.Random();
		}

		private void bNext_Click(object sender, RoutedEventArgs e)
		{
			if (checkVLC(ref _player, AudioDeviceType.MediaPlayer))
				_player.Next();
		}

		private void slider_Mediaplayer_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
		{
			if (checkVLC(ref _player, AudioDeviceType.MediaPlayer))
				_player.setVolume(e.NewValue);
		}

		private void cbMediaPlayerSilent_Checked(object sender, RoutedEventArgs e)
		{
			if (checkVLC(ref _player, AudioDeviceType.MediaPlayer))
				_player.setSilent(cbMediaPlayerSilent.IsChecked.Value);
		}

		private void cbMediaPlayerSilent_Unchecked(object sender, RoutedEventArgs e)
		{
			if (checkVLC(ref _player, AudioDeviceType.MediaPlayer))
				_player.setSilent(cbMediaPlayerSilent.IsChecked.Value);
		}

		private void MediaPlayerSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
		{
			if (checkVLC(ref _player, AudioDeviceType.MediaPlayer))
				_player.setVolume(e.NewValue);
		}
		#endregion

		#region PlaylistTab

		private void bLoadFromFile_Click(object sender, RoutedEventArgs e)
		{
			// As of .Net 3.5 SP1, WPF's Microsoft.Win32.OpenFileDialog class still uses the old style
			VistaOpenFileDialog dialog = new VistaOpenFileDialog();
			dialog.Filter = "All files (*.*)|*.*";
			if (!VistaFileDialog.IsVistaFileDialogSupported)
				MessageBox.Show(this, "Because you are not using Windows Vista or later, you have to fill in the path by yourself", "Not Supported");
			if ((bool)dialog.ShowDialog(this))
			{
				StreamReader streamReader = new StreamReader(dialog.FileName);
				string text = streamReader.ReadToEnd();
				streamReader.Close();

				APIManager a = new APIManager(this);
				a.ParserQueue.Enqueue(text);
			}
		}
		#endregion

		#region BlacklistTab
		#region Filter
		private void Blacklist_KeywordFilter(object sender, System.Windows.Data.FilterEventArgs e)
		{
			BlackListItem t = e.Item as BlackListItem;
			if (t != null)
			{
				if (this.rbKeyword.IsChecked == true && t.Type == BlackListItemType.Keyword)
					e.Accepted = true;
				else
					e.Accepted = false;
			}
		}

		private void Blacklist_PlaylistItemFilter(object sender, System.Windows.Data.FilterEventArgs e)
		{
			BlackListItem t = e.Item as BlackListItem;
			if (t != null)
			{
				if (this.rbPlaylistItem.IsChecked == true && t.Type == BlackListItemType.PlaylistItem)
					e.Accepted = true;
				else
					e.Accepted = false;
			}
		}

		private void Blacklist_UserFilter(object sender, System.Windows.Data.FilterEventArgs e)
		{
			BlackListItem t = e.Item as BlackListItem;
			if (t != null)
			{
				if (this.rbUser.IsChecked == true && t.Type == BlackListItemType.User)
					e.Accepted = true;
				else
					e.Accepted = false;
			}
		}

		private void Blacklist_NoFilter(object sender, System.Windows.Data.FilterEventArgs e)
		{
			BlackListItem t = e.Item as BlackListItem;
			if (t != null)
			{
				if (this.rbAll.IsChecked == true)
					e.Accepted = true;
				else
					e.Accepted = false;
			}
		}
		#endregion

		private void BlacklistFilter_Changed(object sender, RoutedEventArgs e)
		{
			((CollectionViewSource)this.Blacklist.FindResource("cvsTasks")).View.Filter = null;
			int c = 0;

			if (c == 0)
				if (rbKeyword.IsChecked == true)
				{
					c++;
					((CollectionViewSource)this.Blacklist.FindResource("cvsTasks")).Filter += new FilterEventHandler(Blacklist_KeywordFilter);
				}
			if (c == 0)
				if (rbPlaylistItem.IsChecked == true)
				{
					c++;
					((CollectionViewSource)this.Blacklist.FindResource("cvsTasks")).Filter += new FilterEventHandler(Blacklist_PlaylistItemFilter);
				}
			if (c == 0)
				if (rbUser.IsChecked == true)
				{
					c++;
					((CollectionViewSource)this.Blacklist.FindResource("cvsTasks")).Filter += new FilterEventHandler(Blacklist_UserFilter);
				}
			if (c == 0)
				if (rbAll.IsChecked == true)
				{
					c++;
					((CollectionViewSource)this.Blacklist.FindResource("cvsTasks")).Filter += new FilterEventHandler(Blacklist_NoFilter);
				}

			// Refresh the view to apply filters.
			CollectionViewSource.GetDefaultView(edgBlacklist.ItemsSource).Refresh();
		}
		#endregion

		#region FollowerGUIEvents
		private void cbSilentFollower_Checked(object sender, RoutedEventArgs e)
		{
			if (checkVLC(ref _followerAlert, AudioDeviceType.FollowerAlert))
				_followerAlert.setSilent(cbSilentFollower.IsChecked.Value);
		}

		private void cbSilentFollower_Unchecked(object sender, RoutedEventArgs e)
		{
			if (checkVLC(ref _followerAlert, AudioDeviceType.FollowerAlert))
				_followerAlert.setSilent(cbSilentFollower.IsChecked.Value);
		}
		private void slider_Follower_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
		{
			if (checkVLC(ref _followerAlert, AudioDeviceType.FollowerAlert))
				_followerAlert.setVolume(e.NewValue);
		}
		#endregion

		#region SubscriberGUIEvents
		private void cbSubscriber_Checked(object sender, RoutedEventArgs e)
		{
			if (checkVLC(ref _subscriberAlert, AudioDeviceType.SubscriberAlert))
				_subscriberAlert.setSilent(cbSubscriber.IsChecked.Value);
		}

		private void cbSubscriber_Unchecked(object sender, RoutedEventArgs e)
		{
			if (checkVLC(ref _subscriberAlert, AudioDeviceType.SubscriberAlert))
				_subscriberAlert.setSilent(cbSubscriber.IsChecked.Value);
		}

		private void slider_Subscriber_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
		{
			if (checkVLC(ref _subscriberAlert, AudioDeviceType.SubscriberAlert))
				_subscriberAlert.setVolume(e.NewValue);
		}
		#endregion

		#region SoundboardGUIEvents
		private void cbSoundboard_Checked(object sender, RoutedEventArgs e)
		{
			if (checkVLC(ref _soundBoard, AudioDeviceType.Soundboard))
				_soundBoard.setSilent(cbSoundboard.IsChecked.Value);
		}

		private void cbSoundboard_Unchecked(object sender, RoutedEventArgs e)
		{
			if (checkVLC(ref _soundBoard, AudioDeviceType.Soundboard))
				_soundBoard.setSilent(cbSoundboard.IsChecked.Value);
		}

		private void slider_Soundboard_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
		{
			if (checkVLC(ref _soundBoard, AudioDeviceType.Soundboard))
				_soundBoard.setVolume(e.NewValue);
		}
		#endregion

		private void Hyperlink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
		{
			Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
			e.Handled = true;
		}

		/// <summary>
		/// checks, if the specific mediaplayer is initialized, initializes if not and returns false if that failed or it cant start playback
		/// </summary>
		/// <param name="par"></param>
		/// <returns></returns>
		private bool checkVLC(ref MediaPlayer par,AudioDeviceType type)
		{
			if (par == null)
				par = new MediaPlayer(this, type);
			else
				if (!par.playable)
					par = new MediaPlayer(this, type);

			if (!initializedMainWindow) return false;

			if (par != null)
				if (par.playable)
					return true;
			return false;
		}

		private void Button_Click(object sender, RoutedEventArgs e)
		{
			Process.Start(new ProcessStartInfo( ((System.Windows.Controls.Button)e.Source).Content.ToString()));
		}

		public void RequestSongSkip(bool vote)
		{
			_player.Skip(vote);
		}

		public void ForceSongPlay(string url)
		{
			_player.play(url);
		}

		private void bBackup_Click(object sender, RoutedEventArgs e)
		{
			Settings.Instance.createBackup();
		}

		private void tbBackup_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
		{
			VistaFolderBrowserDialog dialog = new VistaFolderBrowserDialog();
			dialog.Description = "Please select a folder.";
			dialog.UseDescriptionForTitle = true; // This applies to the Vista style dialog only, not the old dialog.

			dialog.SelectedPath = Settings.Instance.configFilePath;
			if (!VistaFolderBrowserDialog.IsVistaFolderDialogSupported)
			{
				MessageBox.Show(this, "Because you are not using Windows Vista or later, you have to fill in the path by yourself", "Not Supported");
			}
			if ((bool)dialog.ShowDialog(this))
			{
				tbBackup.Text = dialog.SelectedPath;
			}
		}
	}
}
